<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElDialog, ElButton } from 'element-plus'
import { DifyChat } from '@/components/DifyChat'
import { DIFY_API_BASE_URL } from '@/constants/dify'

const props = defineProps({
  title: {
    type: String,
    default: 'AI智能对话'
  },
  modelValue: {
    type: Boolean,
    default: false
  },
  inputs: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'message-end', 'json-extracted', 'onFinish'])

const dialogVisible = ref(props.modelValue)

// API配置（直接使用默认值）
const apiConfig = reactive({
  apiKey: 'app-XBcoWGd3UPMrLaJMljSdMGdc',
  apiBase: DIFY_API_BASE_URL
})

// 存储最近提取的JSON数据
const extractedJson = ref(null)
const lastMessage = ref('')

// 监听对话框可见性变化
const handleVisibleChange = (val: boolean) => {
  dialogVisible.value = val
  emit('update:modelValue', val)
}

// 监听props.modelValue变化
watch(
  () => props.modelValue,
  (newVal) => {
    dialogVisible.value = newVal
  }
)

// 处理JSON提取事件
const handleJsonExtracted = (jsonData: any) => {
  console.log('DifyDialog: 提取到JSON数据', jsonData)
  extractedJson.value = jsonData
  // 向父组件传递JSON数据
  emit('json-extracted', jsonData)
}

// 处理会话结束事件
const handleMessageEnd = (result: any) => {
  console.log('DifyDialog: 会话结束', result)
  lastMessage.value = result.message

  // 将结果传递给父组件
  emit('message-end', {
    message: result.message,
    response: result.response,
    extractedJson: result.extractedJson || extractedJson.value
  })

  // 同时触发 onFinish 事件以兼容之前的代码
  console.log('回答完成')
  emit('onFinish', {
    message: result.message,
    response: result.response,
    extractedJson: result.extractedJson || extractedJson.value
  })
}

// 单独处理 onFinish 事件（兼容旧代码）
const handleOnFinish = (result: any) => {
  console.log('DifyDialog: onFinish', result)
  // 由于我们已经在 handleMessageEnd 中处理了，这里只做记录
}
</script>

<template>
  <ElDialog
    v-model="dialogVisible"
    :title="title"
    width="70%"
    :before-close="() => handleVisibleChange(false)"
    @update:modelValue="handleVisibleChange"
    destroy-on-close
    append-to-body
    class="dify-dialog"
  >
    <!-- 对话页面 -->
    <div class="chat-container">
      <DifyChat
        :apiKey="apiConfig.apiKey"
        :apiBase="apiConfig.apiBase"
        :title="title"
        :inputs="inputs"
        @message-end="handleMessageEnd"
        @json-extracted="handleJsonExtracted"
        @onFinish="handleOnFinish"
      />
    </div>
  </ElDialog>
</template>

<style lang="less" scoped>
.dify-dialog {
  :deep(.el-dialog__body) {
    padding: 0 !important;
  }
}

.chat-container {
  height: 600px;
  display: flex;
  flex-direction: column;
}
</style>
